package logic

import (
	"context"
	"net/http"
	"path/filepath"
	"usershop/api/pkg"

	"usershop/api/internal/svc"
	"usershop/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type ImageLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewImageLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ImageLogic {
	return &ImageLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ImageLogic) Image(r *http.Request) (resp *types.ResMsg, err error) {
	// todo: 图片上传到七牛云

	//定义文件获取
	file, fileimg, err := r.FormFile("image")
	//判断文件获取时是否成功
	if err != nil {
		return &types.ResMsg{
			Cre:  -1,
			Msg:  "图片获取失败",
			Data: nil,
		}, nil
	}
	//最后关闭文件
	defer file.Close() //用完关闭节省资源

	//判断文件格式
	ext := filepath.Ext(fileimg.Filename)
	if ext != ".png" {
		return &types.ResMsg{
			Cre:  -2,
			Msg:  "图片格式错误",
			Data: nil,
		}, nil
	}

	//判断图片大小
	if fileimg.Size > 1024*1024*3 {
		return &types.ResMsg{
			Cre:  -3,
			Msg:  "图片内存过大",
			Data: nil,
		}, nil
	}

	//调用七牛云 把文件，大小，传进去
	yUn := pkg.QiNiuYun(file, fileimg.Size)
	return &types.ResMsg{
		Cre: 0,
		Msg: "图片上传成功",
		Data: map[string]interface{}{
			"image": yUn, //返回图片生成的路经
		},
	}, nil
}
